//
//  HLCallTool.m
//  YueYue
//
//  Created by hulu001 on 2023/6/20.
//

#import "HLCallTool.h"
#import "HLRtcOptionRequest.h"
#import "HLSystemRingTool.h"
#import "HLCallViewController.h"

@interface HLCallTool ()<HLCallViewControllerDelegate>

@property (nonatomic, strong) HLCallViewController *callViewController;

@end

@implementation HLCallTool


+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static HLCallTool *instance;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}



- (void)joinRoom:(NSString *)roomId fromUser:(nonnull HLUserInfoModel *)fromUser OnVC:(nonnull UIViewController *)onVc
{
    
    if ([self isInCall]) {
        return;
    }
    
    if (![HLHelper authorizationStatus]){
        return;
    }
    
    if (roomId.length == 0 ) {
        [QMUITips showError:@"房间不存在"];
        return;
    }
    
    
    HLRtcOptionRequest *rtcOptionRequest = [[HLRtcOptionRequest alloc] initWithType:HLRtcOptionTypeMaleChat params:@{@"joinRoomId" : roomId}];
    [rtcOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLRtcOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            HLRtcTokenModel *token = [request token];
            if (token.joinToken){
                HLCallViewController *callViewController = [[HLCallViewController alloc] init];
                callViewController.delegate = self;
                callViewController.videoPrice = token.videoPrice;
                callViewController.videoOriginalPrice = token.videoOriginalPrice;
                [[QMUIHelper visibleViewController] presentViewController:callViewController animated:YES completion:nil];
                [callViewController joinRoom:roomId fromUser:fromUser duration:token.videoDuration.integerValue token:token.joinToken];
                self.callViewController = callViewController;
            } else {
                [QMUITips showWithText:@"加入闪聊失败"];
            }
        }
    } failure:nil];

}



- (void)callUser:(HLUserInfoModel *)toUserInfor OnVC:(UIViewController *)onVc
{
    
    if ([self isInCall]) {
        return;
    }
    
    if (![HLHelper authorizationStatus]){
        return;
    }
    
    HLRtcOptionRequest *rtcOptionRequest = [[HLRtcOptionRequest alloc] initWithType:HLRtcOptionTypeVideoCall params:@{@"femaleUserId":toUserInfor.userId, @"callMethod": @"0"}];
    
    [rtcOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLRtcOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            HLRtcTokenModel *token = [request token];
            if (token.joinToken){
                [[HLSystemRingTool shareInstance] playVideoCalling];
                HLCallViewController *callViewController = [[HLCallViewController alloc] init];
                callViewController.delegate = self;
                callViewController.videoPrice = toUserInfor.videoPrice?:token.videoPrice;
                callViewController.videoOriginalPrice = token.videoOriginalPrice;
                [onVc presentViewController:callViewController animated:YES completion:nil];
                if (token.calledUserIdRoomId) {
                    [callViewController joinRoom:token.calledUserIdRoomId fromUser:toUserInfor duration:token.videoDuration.integerValue token:token.joinToken];
                } else {
                    [callViewController callUser:toUserInfor duration:token.videoDuration.integerValue token:token.joinToken];
                }
                self.callViewController = callViewController;
            } else {
                [QMUITips showWithText:@"呼叫失败"];
            }
        }
    } failure:nil];

}


- (void)matchUser:(HLUserInfoModel *)toUserInfor
             OnVC:(UIViewController *)onVc
         callback:(HLCommonCallbackBoolBlock)callback
{
    
    if (![HLHelper authorizationStatus]){
        return;
    }
    
    if ([self isInCall]) {
        return;
    }
    
    NSString *callMethod = @"0";
    
    if (toUserInfor.videoType == HLRtcCallVideoTypeNormal) {
        callMethod = @"0";
    } else if (toUserInfor.videoType == HLRtcCallVideoTypeRandomVideo) {
        callMethod = @"0";
    } else if (toUserInfor.videoType == HLRtcCallVideoTypeHeartVideo) {
       callMethod = @"1";
    }
    // maleUserId
    HLRtcOptionRequest *rtcOptionRequest = [[HLRtcOptionRequest alloc] initWithType:HLRtcOptionTypeVideoCall params:@{@"femaleUserId":toUserInfor.userId, @"callMethod": callMethod}];
    
    [rtcOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLRtcOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            HLRtcTokenModel *token = [request token];
            if (token.joinToken){
                [[HLSystemRingTool shareInstance] playVideoCalling];
                HLCallViewController *callViewController = [[HLCallViewController alloc] init];
                callViewController.delegate = self;
                callViewController.videoPrice = token.videoPrice;
                callViewController.videoOriginalPrice = token.videoOriginalPrice;
                callViewController.joinToken = token.joinToken;
                callViewController.matchCallback = callback;
                [[QMUIHelper visibleViewController] presentViewController:callViewController animated:YES completion:nil];
                if (token.calledUserIdRoomId) {
                    [callViewController joinRoom:token.calledUserIdRoomId fromUser:toUserInfor duration:token.videoDuration.integerValue token:token.joinToken];
                } else {
                    [callViewController callUser:toUserInfor duration:token.videoDuration.integerValue token:token.joinToken];
                }
                self.callViewController = callViewController;
            } else {
                [QMUITips showWithText:@"匹配失败"];
            }
        }
    } failure:nil];
    
}

- (void)calledFormCallUser:(HLUserInfoModel *)fromUserInfor OnVC:(UIViewController *)onVc
{
    
    if (![HLHelper authorizationStatus]){
        return;
    }
    
    if ([self isInCall]) {
        return;
    }

    HLRtcOptionRequest *rtcOptionRequest = [[HLRtcOptionRequest alloc] initWithType:HLRtcOptionTypeMaleJoin params:@{@"femaleUserId" : fromUserInfor.userId}];
    [rtcOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLRtcOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            HLRtcTokenModel *token = [request token];
            if (token.joinToken){
                HLCallViewController *callViewController = [[HLCallViewController alloc] init];
                callViewController.delegate = self;
                callViewController.joinToken = token.joinToken;
                callViewController.avaiableDuration = token.videoDuration.integerValue;
                callViewController.videoPrice = token.videoPrice;
                callViewController.videoOriginalPrice = token.videoOriginalPrice;
                [[QMUIHelper visibleViewController] presentViewController:callViewController animated:YES completion:nil];
                [callViewController calledFormCallUser:fromUserInfor];
                self.callViewController = callViewController;
            } else {
                [QMUITips showWithText:@"接听失败"];
            }
        }
    } failure:nil];
    
}


- (void)accept:(HLUserInfoModel *)fromUserInfor OnVC:(UIViewController *)onVc
{
    // 权限检测
    if (![HLHelper authorizationStatus]){
        return;
    }
    if ([self isInCall]) {
        return;
    }
    
    HLRtcOptionRequest *rtcOptionRequest = [[HLRtcOptionRequest alloc] initWithType:HLRtcOptionTypeMaleJoin params:@{@"femaleUserId" : fromUserInfor.userId}];
    [rtcOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLRtcOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            HLRtcTokenModel *token = [request token];
            if (token.joinToken){
                HLCallViewController *callViewController = [[HLCallViewController alloc] init];
                callViewController.delegate = self;
                callViewController.joinToken = token.joinToken;
                callViewController.avaiableDuration = token.videoDuration.integerValue;
                callViewController.videoPrice = token.videoPrice;
                callViewController.videoOriginalPrice = token.videoOriginalPrice;
                [[QMUIHelper visibleViewController] presentViewController:callViewController animated:YES completion:nil];
                [callViewController accept:fromUserInfor];
                self.callViewController = callViewController;
            } else {
                [QMUITips showWithText:@"接听失败"];
            }
        }
    } failure:nil];
}



- (BOOL)isInCall
{
    if ([HLRunTime shareInstance].isFood) {
        return NO;
    }
    
    UIViewController *viewController = [QMUIHelper visibleViewController];
    if ([viewController isKindOfClass:HLCallViewController.class]) {
        return YES;
    }
    [self checkPresentVC];
    return NO;
}




/*
 检测并dismiss模态
 */
- (void)checkPresentVC
{
    UIViewController *topVC = [QMUIHelper visibleViewController];
    NSLog(@"topVC.presentingViewController = %@", topVC.presentingViewController);
    if (topVC.presentingViewController) {
        [topVC dismissViewControllerAnimated:NO completion:^{
            [self checkPresentVC];
        }];
    }
}


- (void)callDismissWithController:(nonnull HLCallViewController *)viewController
{
    [self.callViewController.smallWindow removeFromSuperview];
    self.callViewController = nil;
}

- (void)callShouldBecomeSmallWithController:(nonnull HLCallViewController *)viewController {
    MJWeakSelf;
    viewController.smallWindow.clickDragViewBlock = ^(HLDragView * _Nonnull dragView) {
        [weakSelf.callViewController.smallWindow removeFromSuperview];
        [[QMUIHelper visibleViewController] presentViewController:weakSelf.callViewController animated:NO completion:nil];
        [weakSelf.callViewController updateRemoteView];
    };
    [[HLUIHelper keyWindow].rootViewController.view addSubview:viewController.smallWindow];
}

@end
